package org.ikross.h2.adapters.gml;

import java.sql.SQLException;

import org.gvsig.h2.gml.GMLFeature;
import org.gvsig.h2.gml.GmlCursor;
import org.h2.index.ExternCursor;
import org.h2.message.Message;
import org.h2.result.Row;
import org.h2.table.Column;
import org.h2.table.TableExtern;
import org.h2.table.TableExternAdapter;

public class CursorGML implements ExternCursor {
	
	private GmlCursor gmlCursor;
	private TableExtern tableExtern;
	
	private Row current;
	private int index;
	
	public CursorGML(TableExtern tableExtern, GmlCursor gmlCursor){
		this.tableExtern=tableExtern;
		this.gmlCursor=gmlCursor;
		
		this.current=null;
		this.index=0;
	}

	public Row get() throws SQLException {
		// TODO Auto-generated method stub
		return this.current;
	}

	public int getPos() {
		// TODO Auto-generated method stub
		return this.index;
	}

	public boolean next() throws SQLException {
		// TODO Auto-generated method stub
		if(!this.gmlCursor.hasNext()){
			this.current=null;
			this.gmlCursor=null;
			return false;
		}
       
		try{
			Object[] objects=((GMLFeature)this.gmlCursor.next()).getAttributeValues();
			current=this.tableExtern.getTemplateRow();
			
			Column[] columns=this.tableExtern.getColumns();

			for(int i=0;i<objects.length;i++){
				current.setValue(i, TableExternAdapter.getValue(columns[i].getType(), objects[i]));
			}

//          Value[] values=(Value[])this.data.nextElement();
//			for(int i=0;i<current.getColumnCount();i++){
//				current.setValue(i, values[i]);
//			}
			
			this.index++;
			return true;
		}
		catch(Exception except){
			throw Message.convert(except);
		}
	}
}
